﻿using System;
using System.Linq;
using StedySoft.SenseSDK;
using System.Windows.Forms;
using StedySoft.SenseSDK.DrawingCE;
using System.IO;
using Microsoft.WindowsMobile.Forms;
using Microsoft.WindowsMobile.PocketOutlook;
using System.Drawing;
using System.ComponentModel;
using Common;
using System.Threading;

namespace MLogix
{
    public partial class SMSFilter
    {
        public const string SMSFILTER = "SMS Filter";
        string contactName = string.Empty;
        string contactsNumber = string.Empty;
        bool messageRuleSelected = false;
        bool contactRuleSelected = false;
        string panel = "NONE";
        private void Form1_Load(object sender, EventArgs e)
        {
            // set the list event handlers
            this._senseListMain.OnShowItemChildren += new SenseListControl.ShowItemChildrenHandler(OnShowItemChildren);
            this._senseListMain.OnHideItemChildren += new SenseListControl.HideItemChildrenHandler(OnHideItemChildren);

            // set the list scroll fluidness
            this._senseListMain.MinimumMovement = 15;
            this._senseListMain.ThreadSleep = 100;
            this._senseListMain.Velocity = .90f;
            this._senseListMain.Springback = .35f;
            AddItems();
        }


        public void OnShowItemChildren(SenseListControl.ISenseListItem Sender)
        {
            if (Sender.Name == "senseUserFilterPanel" || Sender.Name == "senseMessageFilterPanel")
            {
                if (Sender.Name == "senseUserFilterPanel")
                {
                    contactRuleSelected = true; messageRuleSelected = false;
                    _senseAddFilter.LabelText = ReadCustomText.GetString("T_ADDCONTACTFILTER");//"Add Filter for Contacts";
                }
                else
                {
                    contactRuleSelected = false; messageRuleSelected = true;
                    _senseAddFilter.LabelText = ReadCustomText.GetString("T_ADDMESSAGEFILTER");// "Add Filter for messages";
                }
            }
            else
            {
                contactRuleSelected = false; messageRuleSelected = false;
                this._senseListMain.ContextMenu = null;
            }
            if (Sender.Name == "senseViewSentSMSList" || Sender.Name == "senseViewSMSList")
            {
                if (Sender.Name == "senseViewSentSMSList")
                {
                    panel = "SENT";
                }
                else
                {
                    panel = "RECV";
                }
                if (!menuMenu.MenuItems.Contains(menuDel))
                    menuMenu.MenuItems.Add(menuDel);
            }
            else
            {
                panel = "NONE";
                if (menuMenu.MenuItems.Contains(menuDel))
                    menuMenu.MenuItems.Remove(menuDel);
            }
            //_senseReplyText.Text = "";
            menuMenu.Enabled = true;
            menuMenu.Text = ReadCustomText.GetString("T_MENU");// "Menu";
            menuExit.Text = ReadCustomText.GetString("T_BACK");// "Back";

        }

        public void OnHideItemChildren(SenseListControl.ISenseListItem Sender)
        {
            this._senseListMain.ContextMenu = null;
            if ((Sender.Name != "senseViewSMSList" && Sender.Name != "senseViewSentSMSList") || (Sender.Name == "senseViewSMSList" && Auto || Sender.Name == "senseViewSentSMSList" && Auto))
            {
                menuMenu.Enabled = true;
                menuMenu.Text = ReadCustomText.GetString("T_MENU");// "Menu";
                menuExit.Text = ReadCustomText.GetString("T_EXIT");// "Exit";
            }
            if (menuMenu.MenuItems.Contains(menuDel))
                menuMenu.MenuItems.Remove(menuDel);
            panel = "NONE";
        }



        private void menuExit_Click(object sender, EventArgs e)
        {
            bool okayed = false;
            if (e is CancelEventArgs)
                okayed = true;
            if (menuExit.Text.Equals(ReadCustomText.GetString("T_EXIT")))
            {
                if (SenseAPIs.SenseMessageBox.Show(ReadCustomText.GetString("T_EXIT") + "?", SMSFILTER, SenseMessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    NotificationControl.ChangeMessage(_senseCustomMessage.Text.Trim());
                    string[] cRules = new string[_senseUserFilterPanel.Children.Count()];
                    string[] mRules = new string[_senseMessageFilterPanel.Children.Count()];
                    int index = 0;
                    int count = 0;
                    foreach (SenseListControl.ISenseListItem cFilters in _senseUserFilterPanel.Children)
                    {
                        if (count > 3)
                        {
                            cRules[index] = (cFilters as SensePanelItem).PrimaryText.ToString().Trim();
                            index++;
                        }
                        count++;
                    }
                    index = 0;
                    count = 0;
                    foreach (SenseListControl.ISenseListItem mFilters in _senseMessageFilterPanel.Children)
                    {
                        if (count > 2)
                        {
                            mRules[index] = (mFilters as SensePanelItem).PrimaryText.ToString().Trim();
                            index++;
                        }
                        count++;
                    }
                    this.appRunning = false;
                    InterceptorControl.SaveFiltersToReg(cRules, mRules);
                    Application.Exit();

                }
            }
            else
            {
                this._senseListMain.ShowParent();
            }
            if (okayed)
            {
                (e as CancelEventArgs).Cancel = true;
                this.Show();
            }
        }

        string userPass = string.Empty;
        string oldPass = string.Empty;
        void sensePassOK_OnClick(object Sender)
        {

            userPass = _sensePassword.Text.Trim();
            CryptLib.Password = userPass;
            CryptLib.Message = userPass;

            if (newLogin)
            {
                if (_sensePassword.Text.Trim() == _senseConfirm.Text.Trim())
                {
                    if (!changePassword)
                        DBOPS.SensePasswordDB.InsertPassword();
                    else
                        DBOPS.SensePasswordDB.UpdatePassword(oldPass.Trim());
                    if (Auto)
                        SetReadVisible();
                    else
                        SetValidVisibility();
                }
                else
                {
                    SenseAPIs.SenseMessageBox.Show(ReadCustomText.GetString("T_PASSNOTMATCH"), SMSFILTER, SenseMessageBoxButtons.OK);
                    _senseConfirm.Text = "";
                    _sensePassword.Text = "";
                }
            }
            else
            {
                if (CryptLib.EncryptMessage == password)
                {

                    if (changePassword)
                    {
                        newLogin = true;
                        _senseConfirm.Text = "";
                        _sensePassword.Text = "";
                        oldPass = password;
                        SetChangePasswordVisibility();
                    }
                    else
                    {
                         _senseListMain.BeginUpdate();
                        _sensePassword.Visible = false; 
                        if (Auto)
                            SetReadVisible();
                        else
                            SetValidVisibility();
                        RefreshList();
                        _senseListMain.EndUpdate();
                        workerThread.Start();
                    }
                }
                else
                {
                    if (StedySoft.SenseSDK.DrawingCE.SenseAPIs.SenseMessageBox.Show(ReadCustomText.GetString("T_WRONGPASS"), SMSFILTER, SenseMessageBoxButtons.RetryCancel) == DialogResult.Retry)
                    {
                        userPass = "";
                        _sensePassword.Text = "";
                    }
                    else
                    {
                        Application.Exit();
                    }
                }
            }
        }

        void senseChangePass_OnStatusChanged(object Sender, ItemStatus Status)
        {
            if (Status == ItemStatus.On)
            {
                this._sensePassword.LabelText = ReadCustomText.GetString("T_OLDPASS");
                changePassword = true;
            }
            else
            {
                this._sensePassword.LabelText = ReadCustomText.GetString("T_PASSWORD");
                changePassword = false;
            }
        }
        SensePanelComboItem tempDD;
        void senseContactsDD_OnSelectedIndexChanged(object Sender, int Index)
        {
            tempDD = (Sender as SensePanelComboItem);

            _senseViewSMSList.Enabled = false;
            _senseViewSentSMSList.Enabled = false;
            _senseBttnExportSMS.Enabled = false;
            if (Index > 0)
            {
                Thread thFillDetails = new Thread(FetchDetails);
                thFillDetails.IsBackground = true;
                thFillDetails.Start();
            }
        }

        private void ThreadFillContactsDetail()
        {

            //this._senseListMain.BeginUpdate();
            _senseViewSMSList.Enabled = true;
            _senseViewSentSMSList.Enabled = true;
            _senseBttnExportSMS.Enabled = true;
            this._senseViewSMSList.Children.Clear();
            this._senseViewSentSMSList.Children.Clear();
            contactName = tempDD.SelectedItem.Text.Trim();
            contactsNumber = DBOPS.SenseMessagesDB.GetContactsNumber(contactName);
            DBOPS.SenseMessagesDB.GetAllMessagesFromContact(contactName, ref _senseViewSMSList, ref _senseListMain);
            DBOPS.SenseMessagesDB.GetAllSentMessagesToContact(contactName, ref _senseViewSentSMSList, ref _senseListMain);

            _senseViewSMSList.SecondaryText = contactName + " (" + _senseViewSMSList.Children.Count().ToString() + ")";
            _senseViewSentSMSList.SecondaryText = contactName + " (" + _senseViewSentSMSList.Children.Count().ToString() + ")";
            //_senseViewSMSList.Children.Reverse();
            //_senseViewSentSMSList.Children.Reverse();
            //this._senseListMain.EndUpdate();
        }

        private void FetchDetails()
        {
            if (this.InvokeRequired)
            {
                this.Invoke((Action)(() => { ThreadFillContactsDetail(); }));
            }
            else
            {
                ThreadFillContactsDetail();
            }
        }

        void senseCancelTxt_OnClick(object Sender)
        {
            this._senseListMain.ShowParent();
        }




        void _senseBttnAddFilter_OnClick(object Sender)
        {
            string filter = string.Empty;
            SensePanelItem pi;
            if (contactRuleSelected)
            {
                filter = _senseAddFilter.Text.Trim();
                if (!string.IsNullOrEmpty(filter))
                {
                    pi = new SensePanelItem(filter);
                    pi.OnClick += new SensePanelItem.ClickEventHandler(pi_OnClick);
                    pi.PrimaryText = filter;
                    pi.SecondaryText = ReadCustomText.GetString("T_CLICKTODELETE");
                    pi.Tag = "USER";
                    if (!this._senseUserFilterPanel.Children.Contains(pi))
                    {
                        this._senseUserFilterPanel.Children.Add(pi);
                        DBOPS.SenseFilterDB.AddContactFilter(filter);
                        RefreshList();
                    }
                    _senseAddFilter.Text = "";
                }
            }
            else if (messageRuleSelected)
            {
                filter = _senseAddFilter.Text;
                //if (!string.IsNullOrEmpty(filter))
                {
                    pi = new SensePanelItem(filter);
                    pi.OnClick += new SensePanelItem.ClickEventHandler(pi_OnClick);
                    pi.PrimaryText = filter;
                    pi.SecondaryText = ReadCustomText.GetString("T_CLICKTODELETE");
                    pi.Tag = "MESSAGE";
                    if (!this._senseMessageFilterPanel.Children.Contains(pi))
                    {
                        this._senseMessageFilterPanel.Children.Add(pi);

                        DBOPS.SenseFilterDB.AddMessageFilter(filter);
                        RefreshList();
                    }
                    _senseAddFilter.Text = "";
                }
            }

        }

        void pi_OnClick(object Sender)
        {
            if (SenseAPIs.SenseMessageBox.Show(ReadCustomText.GetString("T_DELETEFILTER"), SMSFILTER, SenseMessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                if ((Sender as SensePanelItem).Tag.ToString() == "USER")
                {
                    this._senseUserFilterPanel.Children.Remove((Sender as SensePanelItem));
                    DBOPS.SenseFilterDB.DeleteContactFilter((Sender as SensePanelItem).PrimaryText.Trim());
                }
                if ((Sender as SensePanelItem).Tag.ToString() == "MESSAGE")
                {
                    this._senseMessageFilterPanel.Children.Remove((Sender as SensePanelItem));
                    DBOPS.SenseFilterDB.DeleteMessageFilter((Sender as SensePanelItem).PrimaryText.Trim());
                }
                RefreshList();
            }
        }

        public void RefreshList()
        {
            this._senseListMain.BeginUpdate();
            this._senseListMain.ShowParent();
            this._senseListMain.ShowChildren();
            this._senseListMain.EndUpdate();
        }
        void _senseBttnRefresh_OnClick(object Sender)
        {
            //SenseAPIs.SenseMessageBox.Show("test", "In Event", SenseMessageBoxButtons.OK);
            //TODO: add code to populate dd
            _senseListMain.BeginUpdate();
            if (Sender != null)
            {
                string contact = string.Empty;
                if (NotificationControl.IsNewMessageAvailable(out contact))
                    SenseAPIs.SenseMessageBox.Show(ReadCustomText.GetString("T_NEWMESSAGEFROM") + " " + contact, SMSFILTER, SenseMessageBoxButtons.OK);
            }
            DBOPS.SenseMessagesDB.ClearNewMessages();
            _senseViewSMSList.SecondaryText = "";
            _senseViewSentSMSList.SecondaryText = "";
            int prevIndex = _senseContactsDD.SelectedIndex;

            DBOPS.SenseMessagesDB.FillContactList(ref this._senseContactsDD);
            _senseListMain.EndUpdate();
            _senseContactsDD.SelectedIndex = 0;
            _senseContactsDD.SelectedIndex = prevIndex;
        }
        void _senseBttnLoadFile_OnClick(object Sender)
        {
            FileInfo f = null;
            string category = string.Empty;
            if (contactRuleSelected)
            {
                if (DialogResult.OK == loadFileDia.ShowDialog())
                {
                    f = new FileInfo(loadFileDia.FileName);
                    category = "C";
                }
            }
            else if (messageRuleSelected)
            {
                if (DialogResult.OK == loadFileDia.ShowDialog())
                {
                    f = new FileInfo(loadFileDia.FileName);
                    category = "M";
                }
            }
            if (f != null)
            {
                FileIO.ParseAndLoadFilters(f, category);
            }
            this._senseUserFilterPanel.Children.Clear();
            this._senseMessageFilterPanel.Children.Clear();
            LoadFilter();
            RefreshList();
        }



        void _senseBttnPhoneBook_OnClick(object Sender)
        {
            ChooseContactDialog dlg = new ChooseContactDialog();
            dlg.RequiredProperties = new ContactProperty[] { ContactProperty.AllCommunicationMethods };
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                dlg.AllowNewContactSelection = false;


                string filter = dlg.SelectedContact.FileAs.ToString().Trim();
                SensePanelItem pi;
                if (!string.IsNullOrEmpty(filter))
                {
                    pi = new SensePanelItem(filter);
                    pi.OnClick += new SensePanelItem.ClickEventHandler(pi_OnClick);
                    pi.PrimaryText = filter;
                    pi.SecondaryText = ReadCustomText.GetString("T_CLICKTODELETE");
                    pi.Tag = "USER";
                    if (!this._senseUserFilterPanel.Children.Contains(pi))
                    {
                        this._senseUserFilterPanel.Children.Add(pi);
                        DBOPS.SenseFilterDB.AddContactFilter(filter);
                        RefreshList();
                    }
                }
            }
            dlg.Dispose();
        }
        void _senseCustomSendSMS_OnClick(object Sender)
        {
            string filterNumber = string.Empty;
            string filterName = string.Empty;
            ChooseContactDialog dlg = new ChooseContactDialog();
            dlg.RequiredProperties = new ContactProperty[] { ContactProperty.AllCommunicationMethods };
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                dlg.AllowNewContactSelection = false;
                filterNumber = dlg.SelectedContact.MobileTelephoneNumber.ToString().Trim();
                filterName = dlg.SelectedContact.FileAs.ToString().Trim();
                string action = "NA";
                new MessageEditPanel(filterNumber + "|" + filterName, out action);
                Thread th = new Thread(ThreadRefresh);
                th.IsBackground = true;
                th.Start();
            }
            dlg.Dispose();

        }



        void _senseSilentMode_OnStatusChanged(object Sender, ItemStatus Status)
        {
            if (Status == ItemStatus.On)
            {
                NotificationControl.SetLoudMode();
                _senseSilentMode.Status = ItemStatus.On;
                _senseSilentMode.PrimaryText = ReadCustomText.GetString("T_SOUNDONNEW");// "Play sound on new message";
            }
            else
            {
                NotificationControl.SetSilentMode();
                _senseSilentMode.Status = ItemStatus.Off;
                _senseSilentMode.PrimaryText = ReadCustomText.GetString("T_NOSOUNDONNEW");// "No sound on new message";
            }
        }

        void _senseNotificationEnabled_OnStatusChanged(object Sender, ItemStatus Status)
        {
            if (Status == ItemStatus.On)
            {
                _senseNotificationEnabled.PrimaryText = ReadCustomText.GetString("T_NOTIFICATIONACTIVE");// "Notifiation Active";
                _senseNotificationEnabled.SecondaryText = ReadCustomText.GetString("T_TODISABLEOFF");// "To disable, switch to OFF mode";
                SetSubNotificationVisibleState(false);
                NotificationControl.Enable();
            }
            else
            {
                _senseNotificationEnabled.PrimaryText = ReadCustomText.GetString("T_NOTIFICATIONINACTIVE");// "Notifiation Inactive";
                _senseNotificationEnabled.SecondaryText = ReadCustomText.GetString("T_TOENABLEON");// "To enable, switch to ON mode";
                SetSubNotificationVisibleState(true);
                NotificationControl.Disable();
            }
        }

        void _senseEnableQuickLaunchKey_OnStatusChanged(object Sender, ItemStatus Status)
        {
            if (Status == ItemStatus.On)
            {
                _senseEnableQuickLaunchKey.PrimaryText = ReadCustomText.GetString("T_QKWYENABLED");// "Quick Launch key Enabled";
                _senseEnableQuickLaunchKey.SecondaryText = ReadCustomText.GetString("T_TODISABLEOFF");// "To disable, switch to OFF mode";
                NotificationControl.EnableQuickStartMode();
            }
            else
            {
                _senseEnableQuickLaunchKey.PrimaryText = ReadCustomText.GetString("T_QKEYDISABLED");// "Quick Launch key Disabled";
                _senseEnableQuickLaunchKey.SecondaryText = ReadCustomText.GetString("T_TOENABLEON");// "To enable, switch to ON mode";
                NotificationControl.DisableQuickStartMode();
            }
        }


        void _senseSwitchFilter_OnStatusChanged(object Sender, ItemStatus Status)
        {
            if (Status == ItemStatus.On)
            {
                _senseSwitchFilter.Status = ItemStatus.On;
                _senseSwitchFilter.PrimaryText = ReadCustomText.GetString("T_FILTERINGENABLED");// "Filtering Enabled";
                _senseSwitchFilter.SecondaryText = ReadCustomText.GetString("T_TODISABLEOFF");// "To disable, switch to OFF mode";
                SetSettingsVisibleState(false);
                InterceptorControl.StartInterceptor();

            }
            else
            {
                _senseSwitchFilter.Status = ItemStatus.Off;
                _senseSwitchFilter.PrimaryText = ReadCustomText.GetString("T_FILTERINGDISABLED");// "Filtering Disabled";
                _senseSwitchFilter.SecondaryText = ReadCustomText.GetString("T_TOENABLEON");// "To enable, switch to ON mode";
                SetSettingsVisibleState(true);
                InterceptorControl.ClearInterceptor();
            }
        }

        private int _sipOffset = 0;
        void sip_EnabledChanged(object sender, EventArgs e)
        {
            if (this.sip.Enabled && this._senseListMain.FocusedItem != null)
            {
                SenseListControl.ISenseListItem IItem = this._senseListMain.FocusedItem;
                Rectangle r = IItem.ClientRectangle;
                r.Offset(0, this._senseListMain.Bounds.Top);
                if (IItem is SensePanelTextboxItem)
                {
                    if (r.Bottom > this.sip.VisibleDesktop.Height)
                    {
                        this._sipOffset = Math.Abs(this.sip.VisibleDesktop.Height - r.Bottom);
                        this._senseListMain.ScrollList(-this._sipOffset);
                        this._senseListMain.Invalidate();
                    }
                }
            }
            else
            {
                if (!this._sipOffset.Equals(0))
                {
                    this._senseListMain.ScrollList(this._sipOffset);
                    this._senseListMain.Invalidate();
                }
                this._sipOffset = 0;
            }
        }

        void _senseSaveSentMessage_OnStatusChanged(object Sender, ItemStatus Status)
        {
            if (Status == ItemStatus.On)
            {
                _senseSaveSentMessage.Status = ItemStatus.On;
                _senseSaveSentMessage.PrimaryText = ReadCustomText.GetString("T_SAVESENTMODEON");
                _senseSaveSentMessage.SecondaryText = ReadCustomText.GetString("T_TODISABLEOFF");// "To disable, switch to OFF mode";
                NotificationControl.SetSaveSentMode(true);
            }
            else
            {
                _senseSaveSentMessage.Status = ItemStatus.Off;
                _senseSaveSentMessage.PrimaryText = ReadCustomText.GetString("T_SAVESENTMODEOFF");
                _senseSaveSentMessage.SecondaryText = ReadCustomText.GetString("T_TOENABLEON");// "To enable, switch to ON mode";
                NotificationControl.SetSaveSentMode(false);
            }
        }

        void _senseSaveSentMessageAlert_OnStatusChanged(object Sender, ItemStatus Status)
        {
            if (Status == ItemStatus.On)
            {
                _senseSaveSentMessageAlert.Status = ItemStatus.On;
                _senseSaveSentMessageAlert.PrimaryText = ReadCustomText.GetString("T_SMSSENTALERTON");
                _senseSaveSentMessageAlert.SecondaryText = ReadCustomText.GetString("T_TODISABLEOFF");// "To disable, switch to OFF mode";
                NotificationControl.SetDeliveryMode(true);
            }
            else
            {
                _senseSaveSentMessageAlert.Status = ItemStatus.Off;
                _senseSaveSentMessageAlert.PrimaryText = ReadCustomText.GetString("T_SMSSENTALERTOFF");
                _senseSaveSentMessageAlert.SecondaryText = ReadCustomText.GetString("T_TOENABLEON");// "To enable, switch to ON mode";
                NotificationControl.SetDeliveryMode(false);
            }
        }

        void menuDel_Click(object sender, System.EventArgs e)
        {
            if (SenseAPIs.SenseMessageBox.Show(ReadCustomText.GetString("T_DELETEALL") + " " + contactName, SMSFILTER, SenseMessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                if (panel == "SENT")
                {
                    _senseViewSentSMSList.Children.Clear();
                    DBOPS.SenseMessagesDB.DeleteAllSentContactSMS(contactName);
                }
                else if (panel == "RECV")
                {
                    _senseViewSMSList.Children.Clear();
                    DBOPS.SenseMessagesDB.DeleteAllReceivedContactSMS(contactName);
                }
                FetchDetails();
                RefreshList();
            }
        }

        void _sensePassword_KeyPress(object sender, KeyPressEventArgs e)
        {

            if (e.KeyChar == (char)Keys.Enter)
            {
                e.Handled = true;
                sensePassOK_OnClick(null);
            }
            else
            {
                e.Handled = false;
            }
        }

        void _senseBttnExportSMS_OnClick(object Sender)
        {
            System.Collections.Generic.List<string> CSVList = new System.Collections.Generic.List<string>();
            CSVList.Add("RECEIVED");
            DBOPS.SenseMessagesDB.GetAllMessagesFromContact(contactName, ref CSVList);
            CSVList.Add("SENT");
            DBOPS.SenseMessagesDB.GetAllSentMessagesToContact(contactName, ref CSVList);
            if (FileIO.SaveCSV(CSVList, contactName))
            {
                SenseAPIs.SenseMessageBox.Show(ReadCustomText.GetString("T_CSVGENERATED"), SMSFILTER, SenseMessageBoxButtons.OK);
            }
            else
            {
                SenseAPIs.SenseMessageBox.Show(ReadCustomText.GetString("T_CSVERROR"), SMSFILTER, SenseMessageBoxButtons.OK);
            }
            CSVList.Clear();
            //get all sms from contact
            //get all sent sms to contact
            //save to file
        }


    }
}
